﻿using System;
using System.Globalization;

namespace CoreLibrary.Date {

    public class DateTimeFormatters {

        public static readonly DateTimeFormatters DateTime1  = GetFormat("dd/MM/yy HH:mm:ss");
        public static readonly DateTimeFormatters DateTime2  = GetFormat("yyyy_MM_dd_HH_mm_ss");
        public static readonly DateTimeFormatters DateTime3  = GetFormat("yyyy-MM-dd HH:mm:ss");
        public static readonly DateTimeFormatters DateTime4  = GetFormat("EEEE, dd MMMM yyyy HH:mm:ss");
        public static readonly DateTimeFormatters DateTime5  = GetFormat("dd/MM/yy HH:mm");
        public static readonly DateTimeFormatters DDMMYY     = GetFormat("dd/MM/yy");
        public static readonly DateTimeFormatters DD_MM_YY   = GetFormat("dd-MM-yy");
        public static readonly DateTimeFormatters DD_MM_YYYY = GetFormat("dd-MM-yyyy");
        public static readonly DateTimeFormatters YYYY_MM_DD = GetFormat("yyyy-MM-dd");
        public static readonly DateTimeFormatters DDMMYYYY   = GetFormat("dd/MM/yyyy");
        public static readonly DateTimeFormatters MMYY       = GetFormat("MM/yy");
        public static readonly DateTimeFormatters MMYYYY     = GetFormat("MM/yyyy");
        public static readonly DateTimeFormatters MMMYYYY    = GetFormat("MMM yyyy");
        public static readonly DateTimeFormatters HHMMSS     = GetFormat("HH:mm:ss");

        public string DateFormatString { get; private set; }

        public DateTimeFormatters(string format) {
            DateFormatString = format;
        }

        public DateTime Convert(string dateString, DateTime def) {
            if (string.IsNullOrEmpty(dateString)) {
                return def;
            }
            if (string.IsNullOrEmpty(DateFormatString)) {
                return def;
            }

            DateTime result;
            var d = DateTime.TryParseExact(dateString, DateFormatString, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces,
                                   out result);

            return d ? result : def;
        }

        public string Format(DateTime? dateTime, DateTime def) {
            if (dateTime == null) {
                return Format(def);
            }
            return Format((DateTime) dateTime);
        }

        public string Format(DateTime dateTime) {
            if (string.IsNullOrEmpty(DateFormatString)) {
                return dateTime.ToLongDateString();
            }
            return dateTime.ToString(DateFormatString);
        }

        private static DateTimeFormatters GetFormat(string dateFormatString) {
            return new DateTimeFormatters(dateFormatString);
        }

    }

}